<template>
  <div class="container-box">
    <el-dialog
      :title="title"
      :visible.sync="value"
      width="1200px"
      append-to-body
      custom-class="import-dialog"
      @close="close"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        label-width="120px"
        class="demo-form"
      >
        <el-descriptions title="房间信息"></el-descriptions>
        <el-form-item label="房间名称">
          <div>{{ houseData.premisesAddress }}</div>
        </el-form-item>
        <el-form-item prop="apartmentPictureList" label="房间展示">
          <div class="tips">(可上传图片共9张，默认第一张为主图)</div>
          <!-- <div style="display: flex">
            <div
              v-for="(item, index) in form.apartmentPictureList"
              :key="index"
              class="item-img-box"
            >
              <img class="up-img" :src="item" alt=""/>
              <span class="item-delete">
                <span @click="handleRemove(index)">
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
            <el-upload
              v-if="form.apartmentPictureList.length < 9"
              action="/common/upload"
              list-type="picture-card"
              :auto-upload="true"
              :headers="headers"
              :accept="'image/*'"
              :on-success="onSuccess"
              :show-file-list="false"
            >
              <i slot="default" class="el-icon-plus"></i>
            </el-upload>
          </div> -->
          <image-upload v-model="form.apartmentPictureList" :limit="9" @change="imageUploadChange"/>
        </el-form-item>
        <el-form-item label="房源介绍" prop="apartmentDescription">
          <el-input
            style="width: 600px"
            type="textarea"
            v-model="form.apartmentDescription"
            maxlength="100"
            show-word-limit
          ></el-input>
          <p class="tips">信息用于小程序房源信息介绍</p>
        </el-form-item>
        <el-form-item label="房屋类型" prop="allocationType">
          <el-select v-model="form.allocationType" placeholder="请选择">
            <el-option
              v-for="item in dict.type.allocation_type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签" prop="labelIdList">
          <el-select v-model="form.labelIdList" placeholder="请选择" multiple>
            <el-option
              :label="item.labelName"
              :value="item.labelId"
              v-for="(item, index) in labelList"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="床铺数量" prop="bedNumber">
          <el-input
            v-model="form.bedNumber"
            placeholder="请输入"
            style="width: 220px"
            v-input.int
          ></el-input>
        </el-form-item>
<!--        <el-form-item label="可住人数" prop="checkInNumber">-->
<!--          <el-input-->
<!--            v-model="form.checkInNumber"-->
<!--            placeholder="请输入"-->
<!--            style="width: 220px"-->
<!--            v-input.intp-->
<!--          ></el-input>-->
<!--        </el-form-item>-->
        <el-form-item label="联系方式" prop="contactPhone">
          <el-input
            v-model="form.contactPhone"
            placeholder="请输入"
            style="width: 220px"
            maxlength="11"
            v-input.num
          ></el-input>
          <p class="tips">用于小程序联系房东时拨打的联系电话</p>
        </el-form-item>
        <div class="section">
          <el-descriptions title="房间要求"></el-descriptions>
          <el-form-item
            :label="item.requireName"
            v-for="(item, index) in form.houseRequireList"
            :key="index"
            :prop="'houseRequireList.' + index + '.requireType'"
            :rules="[{ required: true, message: '请选择' }]"
          >
            <el-radio-group
              v-model="form.houseRequireList[index].requireType"
              @change="radioChange"
            >
              <el-radio label="0">允许</el-radio>
              <el-radio label="1">不允许</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-descriptions title="位置信息"></el-descriptions>
          <div class="columns">
            <el-form-item label="景区" prop="attractionsIdList">
              <el-select
                v-model="form.attractionsIdList"
                placeholder="请选择景区"
                filterable
                multiple
              >
                <el-option
                  v-for="(item, index) in attractionsList"
                  :key="index"
                  :label="item.attractionsName"
                  :value="item.attractionsId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="商圈" prop="businessCircleIdList">
              <el-select
                v-model="form.businessCircleId"
                placeholder="请选择商圈"
                filterable
              >
                <el-option
                  v-for="(item, index) in circleList"
                  :key="index"
                  :label="item.businessCircleName"
                  :value="item.businessCircleId"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
          <el-form-item label="位置表述" prop="locationDescription">
            <el-input
              style="width: 600px"
              type="textarea"
              :autosize="{ minRows: 2 }"
              v-model="form.locationDescription"
              maxlength="100"
              show-word-limit
            ></el-input>
          </el-form-item>
          <el-descriptions title="入住设置"></el-descriptions>
          <el-form-item label="房源性质">
            <el-radio-group v-model="form.leaseIntervalType">
              <el-radio label="1">日租</el-radio>
              <el-radio label="2">短租</el-radio>
              <el-radio label="3">长租</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="最少间夜数" prop="leaseIntervalDay" v-if="form.leaseIntervalType === '1'">
            <el-input
              v-model="form.leaseIntervalDay"
              placeholder="请输入"
              type="number"
              style="width: 220px"
              v-input.intp
            ></el-input
            >
            晚
          </el-form-item>
          <el-form-item label="可定范围" prop="leaseScope">
            租客可预定
            <el-select v-model="form.leaseScope" placeholder="请选择">
              <el-option
                v-for="item in timeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            内的日期
          </el-form-item>

          <el-form-item prop="checkInTime" label="入住时间">
            <el-time-select v-model="form.checkInTime" :picker-options="{ start: '00:00', end: '23:59', }"
                            placeholder="选择时间"
            >
            </el-time-select>
          </el-form-item>

          <el-form-item prop="checkOutTime" label="退房时间">
            <el-time-select v-model="form.checkOutTime" :picker-options="{ start: '00:00', end: '23:59', }"
                            placeholder="选择时间"
            ></el-time-select>
          </el-form-item>
          <el-form-item prop="suggestCheckOutTime" label="建议退房时间">
            <el-time-select
              v-model="form.suggestCheckOutTime"
              :picker-options="{
                start: '00:00',
                end: '23:59',
              }"
              placeholder="选择时间"
            >
            </el-time-select>
          </el-form-item>
          <el-form-item label="入住方式" prop="checkInTypeList">
            <el-checkbox-group
              v-model="form.checkInTypeList"
              @change="checkChange"
            >
              <el-checkbox label="1" name="type">实名登记</el-checkbox>
              <el-checkbox label="2" name="type">自助入住</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-descriptions title="服务设施"></el-descriptions>

          <!-- 遍历每个类别 -->
          <div v-for="(items, category) in categorizedFacilities" :key="category">
            <!-- 显示类别名称 -->
            <el-form-item :label="category">
              <!-- Checkbox Group -->
              <el-checkbox-group v-model="categoryOptions[category]">
                <el-row>
                  <el-col :span="4" v-for="item in items" :key="item.value">
                    <el-checkbox :label="item.value" :value="item.value" :key="item.value">{{
                        item.label
                      }}
                    </el-checkbox>
                  </el-col>
                </el-row>

              </el-checkbox-group>
            </el-form-item>
          </div>


          <el-descriptions title="费用设置"></el-descriptions>
          <el-form-item label="房费（元）" prop="housingPriceList">
            <el-table :data="[1]" style="width: 100%">
              <el-table-column
                v-for="(week, index) in form.housingPriceList"
                :label="weekText(week.week)"
                :key="week.week"
              >
                <template slot-scope="scope">
                  <div style="margin-bottom: 20px">
                    <el-form-item
                      label=""
                      label-width="0"
                      :prop="'housingPriceList.' + index + '.housePrice'"
                      :rules="[{ required: true, message: '请输入价格' }]"
                    >
                      <el-input
                        v-model="form.housingPriceList[index].housePrice"
                        type="number"
                        placeholder=""
                      ></el-input>
                    </el-form-item>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>

          <el-form-item label="押金" prop="cashPledge">
            <el-input
              v-model="form.cashPledge"
              type="string"
              placeholder="请输入"
              style="width: 220px"
              v-input.float="2"
              @change="(e)=>this.form.cashPledge = Number(e)"
            ></el-input>
          </el-form-item>
          <el-form-item label="月租金" prop="monthRent">
            <el-input
              v-model="form.monthRent"
              type="string"
              placeholder="请输入"
              style="width: 220px"
              v-input.float="2"
              @change="(e)=>this.form.monthRent = Number(e)"
            ></el-input>
          </el-form-item>
          <el-form-item label="退订规则" prop="unsubscribeRuleId">
            <el-select v-model="form.unsubscribeRuleId" placeholder="请选择">
              <el-option
                v-for="item in ruleList"
                :key="item.unsubscribeRuleId"
                :label="item.unsubscribeRuleName"
                :value="item.unsubscribeRuleId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-descriptions title="显示设置"></el-descriptions>
          <el-form-item label="上下架" prop="apartmentState">
            <el-radio-group v-model="form.apartmentState">
              <el-radio label="0">上架</el-radio>
              <el-radio label="1">下架</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="submitForm">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDecoration,
  listFacilities,
  listPayType,
  getAllocation,
  listAttractions,
  listCircle,
  addHousingAllocation,
  updateHousingAllocation,
  getAllInfoLabel,
  listRange,
  addLabel,
  requireList,
  unsubscribeRule,
  getfacilities
} from '@/api/house/unmount'
import { getContractTemplate } from '@/api/contract/template'
import { getUnsubscribeRule } from '@/api/house/rule'
import calendar from './calendar/index.vue'
import selectRuleDialog from '@/views/house/components/select-rule-dialog.vue'
import selectContractTemplateDialog from '@/views/house/components/select-contractTemplate-dialog.vue'
import { getToken } from '@/utils/auth'
import { serverFacilitiesOptions } from '@/api/base/base-data'

export default {
  props: {
    value: {
      type: Boolean,
      default: false
    },
    houseId: {
      default: undefined
    },
    title: {
      default: '编辑'
    },
    success: {
      type: Function,
      default: () => {
      }
    }
  },
  dicts: ['allocation_type'],
  components: {
    priceCalendar: calendar,
    selectRuleDialog,
    selectContractTemplateDialog
  },
  data() {
    var checkFacilitiesItem = (rule, value, callback) => {
      value.forEach((item) => {
        if (!item.facilitiesNumber || !item.facilitiesPrice) {
          callback(new Error(`${item.facilitiesName}的数量或单价不能为空`))
        }
      })

      if (!value) {
        return callback(new Error('年龄不能为空'))
      }
      callback()
    }
    var checkPriceMap = (rule, value, callback) => {
      if (!this.priceMap.length) callback(new Error(`收费标准不能为空`))
      this.priceMap.forEach((item) => {
        if (!item.timeRangeId || !item.fixedPrice) {
          callback(new Error(`时效收费相关数据不能为空`))
        }
      })
      callback()
    }
    return {
      // mock
      categorizedFacilities: {},
      categoryOptions: {},
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      visible: false,
      headers: {
        Authorization: 'Bearer ' + getToken(),
        ['X-Tenantid']: 1
      },
      //退订规则数据
      unsubscribeRuleData: {},
      //合同数据
      contractTemplateData: {},
      //房屋数据
      houseData: {},
      //装修状况列表
      decorationList: [],
      //押付方式列表
      payTypeList: [],
      // 商圈列表
      circleList: [],
      // 景点列表
      attractionsList: [],
      //标签列表
      labelList: [],
      //价格区间列表
      rangeList: [],

      requireList: [],
      dialogFacilitiesVisible: false,
      facilitiesList: [],
      // facilitieSelected: [],
      facilitiesForm: {
        facilitiesArr: []
      },
      form: {
        remark: null,
        tenantId: null,
        allocationId: null, //配置id
        houseId: null, //房屋id
        unsubscribeRuleId: null, //退订规则id
        inspectionPicture: null,
        apartmentDescription: null, //房屋介绍
        allocationType: null, //房屋类型（1简装套房，2精装套房，3豪装套房）
        labelIds: null,
        labelNames: null,
        bedNumber: null, //床铺数量
        checkInNumber: null, //可住人数
        contactPhone: null, //联系电话
        facilitiesIds: null,
        attractionsIds: null,
        attractionsFullNames: null,
        businessCircleId: null, //商区id
        businessCircleName: '名称', //商区名称
        locationDescription: null, //位置描述
        leaseIntervalDay: null, //最少间夜数
        leaseScope: '3', //可定范围（1=3个月 2=6个月 3=1年 4=2年）
        checkInTime: '15:00', //入住时间hh:dd:ss
        checkOutTime: '12:00', //退房时间hh:dd:ss
        suggestCheckOutTime: '12:00', //建议退房时间hh:dd:ss
        checkInTypeList: ['1'], //入住方式（1实名登记，2自助入住）
        housePrice: null,
        cashPledge: null, //押金
        monthRent: null, //月租金
        apartmentState: '0', //上架状态：0已上架 1已下架
        delFlag: null,
        houseIds: null,
        calendarPriceList: null,
        allocationState: null, //配置状态
        apartmentPictureList: [], //房屋照片路径集合
        inspectionPictureList: ['image'], //验房照片路径集合
        housePriceMap: {
          monday: null,
          tuesday: null,
          wednesday: null,
          thursday: null,
          friday: null,
          saturday: null,
          sunday: null
        }, //房费价格，key为1~7为星期1~星期天
        keyword: null, //关键字搜索
        facilitiesIdList: [], //设施id集合
        labelIdList: null, //标签id集合
        attractionsIdList: null, //景区id集合
        type: [],
        calculate: '',
        housingPriceList: [
          {
            week: '1',
            housePrice: ''
          },
          {
            week: '2',
            housePrice: ''
          },
          {
            week: '3',
            housePrice: ''
          },
          {
            week: '4',
            housePrice: ''
          },
          {
            week: '5',
            housePrice: ''
          },
          {
            week: '6',
            housePrice: ''
          },
          {
            week: '7',
            housePrice: ''
          }
        ]
      },
      timeList: [
        { label: '3个月', value: '1' },
        { label: '6个月', value: '2' },
        { label: '一年', value: '3' },
        { label: '两年', value: '4' }
      ],
      configList: [],
      dialogPriceFormVisible: false,
      priceForm: {},
      calendarPriceList: [],
      //时效收费list
      priceMap: [],
      showCalendar: false,
      dialogSelectRuleVisible: false,
      dialogSelectContractVisible: false,
      customLabelStatus: false,
      customLabelContent: '',
      ruleList: [],
      rules: {
        apartmentPictureList: [
          {
            type: 'array',
            required: true,
            message: '请上传图片',
            trigger: 'change'
          }
        ],
        apartmentType: [
          { required: true, message: '请选择周期类型', trigger: 'blur' }
        ],
        rentStartingTime: [
          { required: true, message: '请输入起租时长', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value == 0) {
                callback(new Error('起租时长不能为0'))
              } else if (this.form.apartmentType == 2 && value < 90) {
                callback(new Error('长租起租时长要大于90天'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        rentableStartTime: [
          {
            required: true,
            message: '请选择日期',
            trigger: 'blur'
          }
        ],
        rentableEndTime: [
          {
            required: true,
            message: '请选择日期',
            trigger: 'blur'
          }
        ],
        checkInTime: [
          {
            required: true,
            message: '请选择入住时间',
            trigger: 'change'
          }
        ],
        checkOutTime: [
          {
            required: true,
            message: '请选择退房时间',
            trigger: 'change'
          }
        ],
        suggestCheckOutTime: [
          {
            required: true,
            message: '请选择建议退房时间',
            trigger: 'change'
          }
        ],
        checkInTypeList: [
          {
            required: true,
            type: 'array',
            message: '请选择入住方式',
            trigger: 'change'
          }
        ],
        unsubscribeRuleId: [
          {
            required: true,
            message: '请选择退订规则',
            trigger: 'change'
          }
        ],
        apartmentState: [
          {
            required: true,
            message: '请选择上下架',
            trigger: 'change'
          }
        ],
        leaseEndTime: [
          {
            required: true,
            message: '请选择退租截止日期日期',
            trigger: 'blur'
          }
        ],
        intervalTime: [
          {
            required: true,
            message: '请输入间隔天数',
            trigger: 'blur'
          }
        ],
        leaseRemindTime: [
          {
            required: true,
            message: '请输入提前天数',
            trigger: 'blur'
          }
        ],
        chargeType: [
          { required: true, message: '请选择收费类型', trigger: 'blur' }
        ],
        priceMap: [{ validator: checkPriceMap, trigger: 'blur' }],
        fixedPrice: [
          { required: true, message: '请输入固定租金', trigger: 'blur' }
        ],
        averageDaily: [
          { required: true, message: '请输入日租金', trigger: 'blur' }
        ],
        monthPrice: [
          { required: true, message: '请输入月租金', trigger: 'blur' }
        ],
        cashPledge: [
          { required: true, message: '请输入押金', trigger: 'blur' }
        ],
        servicePrice: [
          { required: true, message: '请输入服务费', trigger: 'blur' }
        ],
        // baojie: [{ required: true, message: "请输入保洁费", trigger: "blur" }],
        // unsubscribeRuleId: [
        //   { required: true, message: '请选择退订规则', trigger: 'blur' }
        // ],
        templateId: [
          { required: true, message: '请选择关联合同', trigger: 'blur' }
        ],
        stewardPhone: [
          { required: true, message: '请输入房管家电话', trigger: 'blur' }
        ],
        decorationId: [
          { required: true, message: '请选择装修情况', trigger: 'blur' }
        ],
        facilitiesItems: [
          { required: true, message: '房屋配置不能为空', trigger: 'blur' },
          { validator: checkFacilitiesItem, trigger: 'blur' }
        ],
        labelIdList: [
          { required: true, message: '请选择标签', trigger: 'blur' }
        ],
        apartmentDescription: [
          { required: true, message: '请输入房源介绍', trigger: 'blur' }
        ],
        allocationType: [
          { required: true, message: '请选择房屋类型', trigger: 'change' }
        ],
        bedNumber: [
          { required: true, message: '请输入床铺数量', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value <= 0) {
                callback(new Error('床铺数量至少为1'))
              }
              callback()
            }
          }
        ],
        checkInNumber: [
          { required: true, message: '请输入可住人数', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value <= 0) {
                callback(new Error('可住人数至少为1'))
              }
              callback()
            }
          }
        ],
        contactPhone: [
          { required: true, message: '请输入联系方式', trigger: 'blur' },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ],
        leaseIntervalDay: [
          { required: true, message: '请输入最少间夜数', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value < 0) {
                callback(new Error('最少间夜数不能小于0'))
              }
              callback()
            }
          }
        ],
        leaseScope: [
          { required: true, message: '请选择可定范围', trigger: 'change' }
        ],
        housingPriceList: [
          {
            type: 'array',
            required: true,
            message: '请选择可定范围',
            trigger: 'change'
          }
        ]
      },
      priceFormRules: {
        time: [
          {
            validator: (rule, value, callback) => {
              if (!this.calendarPriceList.length) {
                callback(new Error(`请添加日期`))
              }
              this.calendarPriceList.forEach((item) => {
                if (!item.startTime || !item.endTime) {
                  callback(new Error(`开始日期和结束日期不能为空`))
                }
              })
              callback()
            }
          }
        ],
        price: [
          {
            validator: (rule, value, callback) => {
              if (!this.calendarPriceList.length) {
                callback(new Error(`请添加日期`))
              }
              this.calendarPriceList.forEach((item) => {
                if (!item.price) {
                  callback(new Error(`价格不能为空`))
                }
              })
              callback()
            }
          }
        ]
      },
      // 可租时间选择配置
      rentableStartTimeOptions: {
        disabledDate: (time) => {
          let endTime = new Date(this.form['rentableEndTime']).getTime()
          let noRentableStartTime = new Date(
            this.form['noRentableStartTime'] + ' 0:00:00'
          ).getTime()
          // if (!endTime) return false
          return (
            (!!endTime && time.getTime() > endTime) ||
            (noRentableStartTime && time.getTime() == noRentableStartTime)
          )
        }
      },
      rentableEndTimeOptions: {
        disabledDate: (time) => {
          let startTime = new Date(this.form['rentableStartTime']).getTime()
          let noRentableEndTime = new Date(
            this.form['noRentableEndTime'] + ' 0:00:00'
          ).getTime()
          // if (!startTime) return false
          return (
            (!!startTime && time.getTime() < startTime) ||
            (noRentableEndTime && time.getTime() == noRentableEndTime)
          )
        }
      },

      noRentableEndTimeOptions: {
        disabledDate: (time) => {
          let startTime = new Date(this.form['noRentableStartTime']).getTime()
          let rentableEndTime = new Date(
            this.form['rentableEndTime'] + ' 0:00:00'
          ).getTime()
          // if (!startTime) return false
          return (
            (!!startTime && time.getTime() < startTime) ||
            (rentableEndTime && time.getTime() == rentableEndTime)
          )
        }
      }
    }
  },
  computed: {
    generateHouseName() {
      return (row) => {
        let name = ''
        if (row.provinceName) name += row.provinceName
        if (row.cityName) name += row.cityName
        if (row.districtName) name += row.districtName
        if (row.streetName) name += row.streetName

        if (row.estateName) name += row.estateName
        if (row.buildingName) name += row.buildingName + '栋'
        if (row.unitName) name += row.unitName + '单元'
        if (row.roomNumber) name += row.roomNumber + '号'
        return name
      }
    }
  },
  watch: {},
  created() {
    this.init()
  },
  methods: {
    //初始化
    init() {
      this.getrequireList()
      this.getlistUnsubscribeRule()
      this.getListPayType()
      this.getAllInfoLabel()
      this.getListAttractions()
      this.getListCircle()
      //获取详情信息
      this.getHousingAllocation()
      this.getfacilitiesFn()
    },
    getServerFacilitiesOptions() {
      serverFacilitiesOptions().then(res => {
        this.categorizedFacilities = res.data.categorizedFacilities
        this.categoryOptions = res.data.categoryOptions
      })
    },
    handleRemove(index) {
      this.form.apartmentPictureList.splice(index, 1)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    onSuccess(response, file, fileList) {
      this.form.apartmentPictureList.push(response.url)
      console.log(this.form.apartmentPictureList)
    },
    radioChange(e) {
      this.$forceUpdate()
    },
    checkChange(e) {
      console.log(e)
    },
    //新增周边配置
    addConfig() {
      let data = {
        type: '',
        content: ''
      }
      this.configList.push(data)
    },
    //选择退订规则回调
    selectRuleCb(data) {
      this.form.unsubscribeRuleId = data.unsubscribeRuleId
      this.unsubscribeRuleData = data
    },
    //获取退订规则详情
    getRule() {
      if (!this.form.unsubscribeRuleId) return
      let id = this.form.unsubscribeRuleId
      getUnsubscribeRule(id).then((response) => {
        if (!response.data) return
        this.unsubscribeRuleData = response.data
      })
    },
    //选择合同回调
    selectContractCb(data) {
      this.form.templateId = data.templateId
      this.contractTemplateData = data
    },
    //获取合同详情
    getContractTemplate() {
      if (!this.form.templateId) return
      let id = this.form.templateId
      getContractTemplate(id).then((response) => {
        if (!response.data) return
        this.contractTemplateData = response.data
      })
    },

    //获取装修状况
    getListDecoration() {
      listDecoration()
        .then((res) => {
          if (res.code == 200) {
            this.decorationList = res.data
          }
        })
        .catch((err) => {
        })
    },
    //获取押付方式列表
    getListPayType() {
      listPayType().then((response) => {
        if (response.code == 200) {
          this.payTypeList = response.data
        }
      })
    },
    //获取设施列表
    getfacilitiesFn() {
      getfacilities().then((response) => {
        this.facilitiesList = response.data
      })
    },
    //获取种类列表
    getrequireList() {
      requireList().then((response) => {
        let houseRequireList = response.data
        houseRequireList.map((item) => {
          item.requireType = '0'
        })
        this.form.houseRequireList = houseRequireList
      })
    },
    //获取退订规则列表
    getlistUnsubscribeRule() {
      unsubscribeRule().then((response) => {
        if (response.code == 200) {
          this.ruleList = response.data
        }
      })
    },

    //获取商圈
    getListCircle() {
      listCircle().then((response) => {
        if (response.code == 200) {
          this.circleList = response.data
        }
      })
    },
    //获取景点
    getListAttractions() {
      listAttractions().then((response) => {
        if (response.code == 200) {
          this.attractionsList = response.data
        }
      })
    },
    //获取标签
    getAllInfoLabel() {
      getAllInfoLabel().then((response) => {
        if (response.code == 200) {
          this.labelList = response.data
        }
      })
    },
    //添加自定义标签
    addCustomLabel() {
      let value = this.customLabelContent
      if (!value) {
        this.customLabelStatus = false
        return
      }

      let data = {
        labelName: value //标签名
      }
      addLabel(data).then((response) => {
        if (response.code == 200) {
          this.customLabelContent = ''
          this.getAllInfoLabel()
          this.$nextTick(() => {
            this.form.labelIdList.push(response.data.labelId)
          }, 500)
          this.customLabelStatus = false
        }
      })
    },
    //获取价格区间
    getListRange() {
      listRange().then((response) => {
        if (response.code == 200) {
          this.rangeList = response.data
        }
      })
    },
    //展示房屋配置弹窗
    showDialogFacilities() {
      listFacilities().then((res) => {
        if (res.code == 200) {
          this.facilitiesList = res.data
          this.facilitiesForm.facilitiesArr = []
          this.dialogFacilitiesVisible = true
        }
      })
    },
    closeFacilitiesDialog(done) {
      this.$refs.facilitiesForm.resetFields()
      this.facilitiesForm.facilitiesArr = []
      done()
    },
    // 选择设施
    selectFacilities() {
      let list = this.facilitiesList.filter((item) =>
        this.facilitiesForm.facilitiesArr.includes(item.facilitiesId)
      )
      this.form.facilitiesItems = list.map((item) => {
        return {
          facilitiesId: item.facilitiesId,
          facilitiesName: item.facilitiesName,
          facilitiesPrice: item.facilitiesPrice,
          facilitiesNumber: undefined
        }
      })
      this.form.facilitiesItems = this.form.facilitiesItems
      this.dialogFacilitiesVisible = false
    },
    //移除设施项
    removeFacitieItem(index) {
      this.form.facilitiesItems.splice(index, 1)
    },
    //展示价格日历
    showCalendarPrice() {
      let calendarPriceList = this.form.calendarPriceList
        ? JSON.parse(JSON.stringify(this.form.calendarPriceList))
        : []

      for (let index = 0; index < calendarPriceList.length; index++) {
        calendarPriceList[index]['endTimeOptions'] = {
          disabledDate: (time) => {
            let startTime = new Date(
              calendarPriceList[index].startTime
            ).getTime()
            // if (!startTime) return false
            return !!startTime && time.getTime() < startTime
          }
        }
        calendarPriceList[index]['startTimeOptions'] = {
          disabledDate: (time) => {
            let endTime = new Date(calendarPriceList[index].endTime).getTime()
            // if (!endTime) return false
            return !!endTime && time.getTime() > endTime
          }
        }
      }
      this.calendarPriceList = calendarPriceList
      this.dialogPriceFormVisible = true
    },
    //添加收费标准字段
    addPriceMap() {
      this.priceMap.push({
        timeRangeId: null,
        fixedPrice: null
      })
    },
    removePriceMap(index) {
      this.priceMap.splice(index, 1)
    },
    //确认价格日历
    addCalendarPrice() {
      this.$refs['priceForm'].validate((valid) => {
        if (valid) {
          this.dialogPriceFormVisible = false
        }
      })
    },
    //移除项价格日历项
    removePriceCalendar(index) {
      this.calendarPriceList.splice(index, 1)
    },
    changePriceCalendar(index, type) {
      if (type == 'startTime') {
        let startTime = new Date(
          this.calendarPriceList[index].startTime
        ).getTime()
        this.calendarPriceList[index]['endTimeOptions'] = {
          disabledDate: (time) => {
            return time.getTime() < startTime
          }
        }
      }
      if (type == 'endTime') {
        let endTime = new Date(this.calendarPriceList[index].endTime).getTime()
        this.calendarPriceList[index]['startTimeOptions'] = {
          disabledDate: (time) => {
            return time.getTime() > endTime
          }
        }
      }
      this.$forceUpdate()
    },
    //重置表单
    reset() {
      this.unsubscribeRuleData = {}
      this.contractTemplateData = {}
      this.houseData = {}
      this.priceMap = []
      this.customLabelContent = ''
      this.customLabelStatus = false
      this.form = this.$options.data().form
    },
    weekText(key) {
      switch (key) {
        case '1':
          return '周一'
          break
        case '2':
          return '周二'
          break
        case '3':
          return '周三'
          break
        case '4':
          return '周四'
          break
        case '5':
          return '周五'
          break
        case '6':
          return '周六'
          break
        case '7':
          return '周日'
          break

        default:
          return '周日'
          break
      }
    },
    //获取详情信息
    async getHousingAllocation() {
      await this.getServerFacilitiesOptions()
      getAllocation(this.houseId)
        .then((response) => {
          //房屋数据渲染
          this.houseData = response.data.house
          this.form.houseId = response.data.house.houseId
          if (response.data.houseId) {
            this.form = response.data
          }
          if (!response.data.facilitiesIdList) {
            this.form.facilitiesIdList = []
          } else {
            let facilitiesIdList = response.data.facilitiesIdList
            for (const category in this.categorizedFacilities) {
              this.categorizedFacilities[category].forEach(item => {
                if (facilitiesIdList.includes(item.value)) {
                  this.categoryOptions[category].push(item.value)
                }
              })
            }
            console.log(this.categoryOptions)
          }
        })
        .catch((err) => {
        })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const selectedOption = this.circleList.find(
            (option) => option.businessCircleId === this.form.businessCircleId
          )
          const businessCircleName = selectedOption
            ? selectedOption.businessCircleName
            : ''
          this.form.businessCircleName = businessCircleName
          // categoryOptions处理
          const facilitiesArr = []
          for (const key in this.categoryOptions) {
            if (Array.isArray(this.categoryOptions[key])) {
              facilitiesArr.push(...this.categoryOptions[key])
            }
          }
          if (facilitiesArr.length > 0) {
            this.form.facilitiesIdList = facilitiesArr
            this.form.facilitiesIds = facilitiesArr.join(',')
          }
          if (this.form.allocationId != undefined) {
            updateHousingAllocation(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功')
              this.$emit('success')
              this.close()
            })
          } else {
            addHousingAllocation(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功')
              this.$emit('success')
              this.close()
            })
          }
        }
      })
    },
    //关闭
    close() {
      this.$emit('input', false)
    },
    // 点击商品图
    modalPicTap(tit, num) {
      const _this = this
      if (_this.isDisabled) return
      this.$modalUpload(
        function(img) {
          console.log('img', img)
          _this.imageList = img
        },
        tit,
        'content'
      )
    },
    //上传图片改变回调
    imageUploadChange(data) {
      this.form.apartmentPictureList = data.map(item => item.url)
    }
  }
}
</script>

<style lang="scss" scoped>
//弹出层的高度
.import-dialog {
  height: auto;
  max-height: 80vh;
  overflow-y: auto;

  .header {
    .title {
      padding: 10px 30px;
      margin-bottom: 30px;
      font-weight: bold;
    }
  }

  .demo-form {
    .line {
      text-align: center;
    }
  }

  .expense {
    color: #02a7f0;

    .icon {
      font-size: 30px;
      margin-right: 5px;
      cursor: pointer;
    }

    .price-handle {
      margin: 0 40px;
      cursor: pointer;
    }

    .calendar {
      cursor: pointer;
    }
  }

  .facilities {
    .icon {
      color: #02a7f0;
      font-size: 30px;
      margin-right: 5px;
      cursor: pointer;
      line-height: 36px;
    }

    .facilities-item {
      display: flex;

      .item-label {
        text-align: right;
        margin-right: 10px;
      }
    }
  }

  .dialog-footer {
    text-align: center;
  }
}

//弹出层里内容的高度
::v-deep .el-dialog__body {
  max-height: 80vh !important;
  overflow-y: auto;
}

.section {
  .label {
    display: flex;
    margin-bottom: 30px;
    font-size: 16px;
    align-items: center;

    label {
      display: block;
      width: 80px;
      text-align: right;

      &.dot::before {
        content: "*";
        color: #ff4949;
        margin-right: 4px;
      }
    }

    .icon {
      color: #02a7f0;
      font-size: 30px;
      margin-left: 30px;
      cursor: pointer;
    }
  }

  .tips {
    color: #aaaaaa;
  }
}

.priceDialog {
  .form-container {
    display: flex;
    justify-content: space-around;
    align-items: center;

    .prcieForm {
      border: 1px solid #e3e3e3;
      padding: 30px 20px;
      margin-bottom: 30px;
      flex: 1;
      margin-right: 10px;
    }

    .icon {
      color: #02a7f0;
      font-size: 30px;
      cursor: pointer;
    }
  }

  .dialog-footer {
    text-align: center;
  }
}

.facilitiesDialog {
  .dialog-footer {
    text-align: center;
  }
}

.columns {
  display: grid;
  grid-template-columns: 1fr 1fr;
}

.week {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
}

.item-img-box {
  position: relative;
  border: 1px solid #aaaaaa;
  width: 148px;
  height: 148px;
  margin-right: 10px;
  border-radius: 4px;
  overflow: hidden;

  .up-img {
    width: 148px;
    height: 148px;
  }

  .item-delete {
    position: absolute;
    left: 50%;
    top: 50%;
    z-index: 99;
    transform: translate(-50%, -50%);
    font-size: 32px;
    color: #ff4949;
    cursor: pointer;
  }
}
</style>
